<?php

namespace app\http\middleware;

use app\exceptions\OrdinaryException;
use think\{
    Exception,facade\Cache,Request as OriginRequest,facade\Session
};

class AuthUpdate
{
    /**
     * @throws OrdinaryException
     */
    public function handle(OriginRequest $request, \Closure $next)
    {
        $adminInfo = $request->userInfo;
        if ( $adminInfo['type'] != 1 ) {
            $cacheName = Session::get('gmars_rbac_permission_name');
            Cache::rm('_RBAC_PERMISSION_CACHE_' . $adminInfo['id']);
            if (empty($cacheName)) {
                $this->again($adminInfo['id']);
            } else {
                $permissionList = Cache::get($cacheName);
                if (empty($permissionList)) {
                    $this->again($adminInfo['id']);
                }
            }
        }
        return $next($request);
    }

    /**
     * 重新缓存权限节点
     * @param int $id 用户ID
     * @throws OrdinaryException
     */
    private function again( int $id )
    {
        try {
            app('rbac')->cachePermission($id);
        } catch (Exception $exception) {
            throw new OrdinaryException( $exception->getMessage() );
        }
    }
}
